package com.wn.user.handler;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Component
public class UrlBlockHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {
        String msg = null;
         if(e instanceof FlowException){
            msg = "接口被限流";
        }else if(e instanceof DegradeException){
            msg = "接口被熔断,稍后再试";
        }else if(e instanceof ParamFlowException){
            msg = "热点参数限流";
        }else if(e instanceof SystemBlockException){
            msg = "系统规则限流";
        }else if(e instanceof AuthorityException){
            msg = "系统授权限流";
        }
        httpServletResponse.setStatus(500);
        httpServletResponse.setCharacterEncoding("utf-8");
        httpServletResponse.setContentType("application/json;charset=utf-8");
        ObjectMapper mapper = new ObjectMapper();
        Map map = new HashMap<>();
        map.put("code",500);
        map.put("message",msg);
        mapper.writeValue(httpServletResponse.getWriter(),map);
    }
}